<template>
  <div class="app-container">

    <div class="header-section">
      <div class="name-input-wrapper">
        <span class="required-mark">*</span>
        <span class="paper-name-label">白皮书名称</span>
        <el-form :model="form" :rules="rules" ref="nameFormRef" inline>
          <el-form-item prop="whitePaperName" class="name-form-item">
            <el-input v-model="form.whitePaperName" placeholder="请输入白皮书名称" size="small" class="paper-name-input"
              :border="false" maxlength="50">
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="full-divider"></div>
    </div>

    <div class="progress-section">
      <div class="custom-steps-container">
        <el-steps :active="activeStep" finish-status="primary" class="custom-steps" size="default" ref="stepsRef">
          <el-step v-for="(step, index) in steps" :key="index" :title="step"
            :class="{ 'step-item': true, 'third-step': index === 2 }"></el-step>
        </el-steps>
      </div>
    </div>

    <div :class="['form-section',
      currentComponent === 'PaperOutline' ? 'wide-form' : '',
      currentComponent === 'ResearchAnalysis' ? 'full-width-form' : '']">
      <component :is="currentComponent" :form-data="formData" :white-paper-name="form.whitePaperName"
        :project-id="projectId" @update:formData="handlePaperOutlineUpdate" @updateForm="handleOtherComponentUpdate"
        ref="stepComponentRef" :key="`${currentComponent}-${projectId}-${activeStep}`"
        />
    </div>

    <div class="button-group">
      <el-button @click="activeStep === 0 ? goToHome() : prevStep()" size="small">
        {{ activeStep === 0 ? '取消' : '上一步' }}
      </el-button>
      <el-button type="primary" @click="nextStep" v-if="activeStep != steps.length - 1" size="small">
        {{ activeStep === 2 ? '开始调研' : '下一步' }}
      </el-button>
      <el-button type="primary" @click="submitAll" v-if="activeStep === steps.length - 1" size="small"
        :loading="loading">
        开始调研
      </el-button>
    </div>
  </div>
</template>

<script>
import ProjectInfo from './components/ProjectInfo.vue'
import WriteRequire from './components/WriteRequire.vue'
import PaperOutline from './components/PaperOutline.vue'
import ResearchAnalysis from './components/ResearchAnalysis.vue'
import { addProject, getProject, addChapter, startTask } from '@/api/whitepaper/myproject'

export default {
  name: 'WhitepaperForm',
  components: {
    ProjectInfo,
    WriteRequire,
    PaperOutline,
    ResearchAnalysis
  },
  data() {
  return {
    activeStep: 0,
    formData: {
      whitePaperProject: {},
      whitePaperRequire: {},
      paperOutline: { chapters: [] },
      whitePaperChapters: []
    },
    projectId: 0,
    steps: ['项目信息', '编写要求', '白皮书大纲', '调研/分析'],
    stepComponents: ['ProjectInfo', 'WriteRequire', 'PaperOutline', 'ResearchAnalysis'],
    form: { whitePaperName: '' },
    rules: {
      whitePaperName: [
        { required: true, message: '请输入白皮书名称', trigger: ['blur', 'change', 'submit'] },
        { max: 50, message: '白皮书名称长度不超过50个字符', trigger: ['blur', 'change', 'submit'] }
      ],
    },
    loading: false 
  }
},
  computed: {
    currentComponent() {
      return this.stepComponents[this.activeStep]
    }
  },
  created() {
    this.activeStep = Number(this.$route.query.step) || 0;
    this.projectId = Number(this.$route.query.projectId) || 0;
    if (this.projectId > 0) {
      this.loadProjectData();
    }
  },
  mounted() {
    this.hideSidebar()
    this.adjustMainContent()
    document.body.style.overflow = 'hidden'
    document.documentElement.style.overflow = 'hidden'
    this.$nextTick(() => {
      this.setStepStyles()
      this.ensureChaptersNotEmpty()
    })
  },
  watch: {
    $route: {
      handler(newRoute) {
        this.hideSidebar()
        this.adjustMainContent()
        const newStep = Number(newRoute.query.step) || 0;
        const newProjectId = Number(newRoute.query.projectId) || 0;
        if (newStep !== this.activeStep) {
          this.activeStep = newStep;
        }
        if (newProjectId !== this.projectId) {
          this.projectId = newProjectId;
          if (this.projectId > 0) {
            this.loadProjectData();
          }
        }
      },
      immediate: true,
      deep: true
    },
    activeStep() {
      this.$nextTick(() => {
        this.setStepStyles()
        this.ensureChaptersNotEmpty()
      })
    },
    'formData.whitePaperProject': { deep: true, handler: () => { } },
    'formData.whitePaperChapters': {
      deep: true,
      handler() {
        this.ensureChaptersNotEmpty()
      }
    }
  },
  beforeDestroy() {
    this.restoreSidebar()
    this.restoreMainContent()
    document.body.style.overflow = ''
    document.documentElement.style.overflow = ''
  },
  methods: {
    updateRouteParams() {
      const query = {
        step: this.activeStep,
        projectId: this.projectId
      };

      if (this.$route.query.step !== String(this.activeStep) ||
        this.$route.query.projectId !== String(this.projectId)) {
        this.$router.replace({
          query
        });
      }
    },
    ensureChaptersNotEmpty() {
      if (!this.formData.whitePaperChapters || this.formData.whitePaperChapters.length === 0) {
        this.formData.whitePaperChapters = [{
          chapterName: "",
          sort: 1,
          delFlag: "0",
          outlineList: [{
            title: "",
            dataSource: "",
            collectionRequirements: "",
            aiAnalyseResult: "",
            fianlAnalyseResult: "",
            sort: 1,
            delFlag: "0"
          }]
        }];
      }
    },
    async loadProjectData() {
      try {
        const res = await getProject(this.projectId);
        const projectData = res.data?.data || res.data || res;
        if (projectData) {
          this.form.whitePaperName = projectData.whitePaperName
            ? projectData.whitePaperName.length > 50
              ? projectData.whitePaperName.slice(0, 50)
              : projectData.whitePaperName
            : '';
          this.formData.whitePaperProject = {
            orgName: projectData.orgName || '',
            industry: projectData.industry || '',
            address: projectData.address || '',
            email: projectData.email || '',
            officialWebsite: projectData.officialWebsite || '',
            officialAccountImgUrl: projectData.officialAccountImgUrl || '',
            briefIntroduction: projectData.briefIntroduction || ''
          };
          this.formData.whitePaperRequire = projectData.whitePaperRequire || {};
          this.formData.paperOutline = projectData.paperOutline || { chapters: [] };
          this.formData.whitePaperChapters = projectData.whitePaperChapters || [];
        }
      } catch (err) {
        this.$message.error("加载项目数据失败");
        console.error("加载失败：", err);
      }
    },
    hideSidebar() {
      const sidebarSelectors = ['.sidebar', '.sidebar-container', '.el-layout__sider', '.sidebar-wrap']
      sidebarSelectors.forEach(selector => {
        const el = document.querySelector(selector)
        if (el) {
          el.style.visibility = 'hidden'
          el.style.width = '0px !important'
          el.style.height = '0px !important'
          el.style.padding = '0 !important'
          el.style.margin = '0 !important'
          el.style.overflow = 'hidden !important'
        }
      })
    },
    restoreSidebar() {
      const sidebarSelectors = ['.sidebar', '.sidebar-container', '.el-layout__sider', '.sidebar-wrap']
      sidebarSelectors.forEach(selector => {
        const el = document.querySelector(selector)
        if (el) {
          el.style.visibility = ''
          el.style.width = ''
          el.style.height = ''
          el.style.padding = ''
          el.style.margin = ''
          el.style.overflow = ''
        }
      })
    },
    adjustMainContent() {
      const appMain = document.querySelector('.app-main')
      const mainContainer = document.querySelector('.main-container')
      const layoutContent = document.querySelector('.el-layout__content')

      if (appMain) { appMain.style.marginLeft = '0px !important'; appMain.style.width = '100% !important'; appMain.style.padding = '0 !important'; }
      if (mainContainer) { mainContainer.style.width = '100% !important'; mainContainer.style.overflow = 'hidden !important'; }
      if (layoutContent) { layoutContent.style.marginLeft = '0px !important'; layoutContent.style.width = '100% !important'; }
    },
    restoreMainContent() {
      const appMain = document.querySelector('.app-main')
      const mainContainer = document.querySelector('.main-container')
      const layoutContent = document.querySelector('.el-layout__content')

      if (appMain) { appMain.style.marginLeft = ''; appMain.style.width = ''; appMain.style.padding = ''; }
      if (mainContainer) { mainContainer.style.width = ''; mainContainer.style.overflow = ''; }
      if (layoutContent) { layoutContent.style.marginLeft = ''; layoutContent.style.width = ''; }
    },
    prevStep() {
      this.activeStep--;
      this.updateRouteParams();
    },
    goToHome() { window.location.href = '/index'; },
    async nextStep() {
      if (this.activeStep === 0) {
        this.$refs.nameFormRef.validate(async (valid) => {
          if (valid) await this.validateComponentAndNext()
        })
      } else {
        await this.validateComponentAndNext()
      }
    },
   async validateComponentAndNext() {
  const currentRef = this.$refs.stepComponentRef
  if (currentRef && currentRef.validate) {
    currentRef.validate(async (valid) => {
      if (valid) {
        if (this.activeStep === 2) {
          try {
            await currentRef.submitChapters();
            
            this.activeStep++;
            this.updateRouteParams();
            
          } catch (err) {
            this.$message.error(`章节提交失败：${err.message || '未知错误'}`);
            return;
          }
        } else {
          // 其他步骤跳转逻辑保持不变
          if (this.activeStep === 0) {
            if (this.projectId && this.projectId > 0) {
              this.activeStep++;
              this.updateRouteParams();
              return;
            }

            const projectInfo = this.formData.whitePaperProject || {}
            const submitData = {
              whitePaperName: this.form.whitePaperName,
              orgName: projectInfo.orgName || '',
              industry: projectInfo.industry || '',
              address: projectInfo.address || '',
              email: projectInfo.email || '',
              officialWebsite: projectInfo.officialWebsite || '',
              officialAccountImgUrl: projectInfo.officialAccountImgUrl || '',
              briefIntroduction: projectInfo.briefIntroduction || '',
              projectStatus: '0',
              delFlag: '0'
            }
            try {
              const res = await addProject(submitData)
              const businessCode = res.data?.code ?? res.code ?? 200
              if (businessCode === 200) {
                this.projectId = res.data?.data || res.data || res
                this.activeStep++
                this.updateRouteParams();
              } else {
                const errorMsg = res.data?.msg || res.data?.message || res.msg || res.message || '未知业务错误'
                throw new Error(errorMsg)
              }
            } catch (err) {
              this.$message.error(`项目信息提交失败：${err.message}`);
            }
          } else {
            this.activeStep++
            this.updateRouteParams();
          }
        }
      } else {
        this.$message.error('请核对是否填写完整！');
      }
    })
  } else {
    this.activeStep++
    this.updateRouteParams();
  }
},
    // 等待第四步组件数据加载完成
waitForResearchLoaded() {
  return new Promise((resolve) => {
    let checkCount = 0;
    const maxCheckCount = 75; // 15秒超时
    
    const checkLoaded = () => {
      const researchRef = this.$refs.stepComponentRef;
      checkCount++;
      
      if (!researchRef || (researchRef.validProjectId || 0) <= 0) {
        console.log('子组件未渲染或项目ID无效，结束等待');
        resolve();
        return;
      }
      
      if (
        researchRef && 
        (!researchRef.isLoading || 
         researchRef.researchList.length > 0 || 
         researchRef.retryCount >= researchRef.maxRetry)
      ) {
        resolve();
      } else if (checkCount >= maxCheckCount) {
        this.$message.warning('调研任务加载超时，将显示现有数据');
        resolve();
      } else {
        if (researchRef && !researchRef.isLoading && researchRef.researchList.length === 0) {
          researchRef.initTaskList(true);
        }
        setTimeout(checkLoaded, 200);
      }
    };
    
    setTimeout(checkLoaded, 500);
  });
},
    handlePaperOutlineUpdate(newFormData) {
      if (newFormData.whitePaperChapters) {
        this.formData.whitePaperChapters = newFormData.whitePaperChapters.length > 0
          ? [...newFormData.whitePaperChapters]
          : this.formData.whitePaperChapters;
      }
      this.formData = { ...this.formData, ...newFormData };
    },
    handleOtherComponentUpdate(newFormData) {
      this.formData = {
        ...this.formData,
        whitePaperRequire: newFormData.whitePaperRequire
          ? { ...newFormData.whitePaperRequire }
          : this.formData.whitePaperRequire,
        whitePaperProject: newFormData.whitePaperProject
          ? { ...this.formData.whitePaperProject, ...newFormData.whitePaperProject }
          : this.formData.whitePaperProject
      };
    },
    async submitAll() {
      if (!this.projectId || this.projectId <= 0) {
        this.$message.error('项目ID无效，无法启动调研任务');
        return;
      }

      this.loading = true;
      try {
        const res = await startTask({ projectId: this.projectId });
        const businessCode = res.data?.code ?? res.code ?? 200;
        if (businessCode === 200) {
          this.$message.success('调研任务启动成功！');
          window.location.href = `/whitepaper/detail?id=${this.projectId}`;
        } else {
          const errorMsg = res.data?.msg || res.data?.message || res.msg || res.message || '调研任务启动失败';
          throw new Error(errorMsg);
        }
      } catch (err) {
        this.$message.error(`调研任务启动失败：${err.message}`);
        console.error('startTask接口调用失败：', err);
      } finally {
        this.loading = false;
      }
    },
    setStepStyles() {
      const stepItems = document.querySelectorAll('.step-item')
      stepItems.forEach((item, index) => {
        const icon = item.querySelector('.el-step__icon')
        const title = item.querySelector('.el-step__title')
        if (icon && title) {
          icon.style.width = '28px'; icon.style.height = '28px'; icon.style.borderRadius = '50%';
          icon.style.display = 'flex'; icon.style.alignItems = 'center'; icon.style.justifyContent = 'center';
          icon.style.border = 'none'; icon.innerHTML = '';

          if (index < this.activeStep) {
            icon.style.backgroundColor = '#dff1ff';
            icon.innerHTML = '<i class="el-icon-check" style="color: #1E60FA; font-size: 16px;"></i>';
            title.style.color = '#0C1124';
          } else if (index === this.activeStep) {
            icon.style.backgroundColor = '#1E60FA'; icon.style.color = 'white';
            icon.innerHTML = (index + 1).toString(); title.style.color = '#1E60FA';
            icon.style.zIndex = '999';
          } else {
            icon.style.backgroundColor = '#CED4E0'; icon.style.color = '#fff';
            icon.innerHTML = (index + 1).toString(); title.style.color = '#ACB9CD';
          }

          title.style.fontSize = '14px';
          title.style.whiteSpace = 'nowrap';
        }

        if (index === 3) {
          item.style.transform = 'translateX(20px)';
          item.style.transition = 'transform 0.2s';
        } else {
          item.style.transform = 'none';
        }

        if (index < stepItems.length - 1) {
          let customLine = item.querySelector('.custom-step-line')
          if (!customLine) {
            customLine = document.createElement('div'); customLine.className = 'custom-step-line'; item.appendChild(customLine);
          }
          customLine.style.position = 'absolute';
          customLine.style.left = index === 2 ? 'calc(100% - 80px)' : 'calc(100% - 100px)';
          customLine.style.top = '14px';
          customLine.style.width = '50%';
          customLine.style.height = '0px';
          customLine.style.borderTop = '2px dashed #D8DFEB';
          customLine.style.zIndex = '1';
        }
      })
    }
  }
};
</script>

<style scoped>
.app-container {
  width: 100vw !important;
  height: 100vh !important;
  position: absolute !important;
  top: 0 !important;
  left: 0 !important;
  z-index: 999 !important;
  box-sizing: border-box;
  overflow: hidden;
  padding: 60px 20px 80px;
  background-color: #ffffff !important;
  overflow-x: hidden !important;
}

.header-section {
  margin-bottom: 10px;
  width: 100%;
  box-sizing: border-box;
  background-color: #ffffff !important;
  overflow-x: hidden !important;
}

.name-input-wrapper {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 8px;
  margin-bottom: 16px;
  width: 100%;
  flex-wrap: nowrap;
}

.required-mark {
  color: red;
  font-size: 12px;
  line-height: 1;
}

.paper-name-label {
  font-size: 12px;
  color: #333;
  white-space: nowrap;
  line-height: 1;
}

::v-deep .el-form--inline {
  display: flex;
  align-items: center;
  width: auto;
  flex: 1;
}

.name-form-item {
  width: 100%;
  margin-bottom: 0 !important;
  position: relative;
}

.paper-name-input {
  width: 510px;
  max-width: 100%;
}

.paper-name-input .el-input__inner {
  background-color: #EEF4FA !important;
  border: none !important;
  box-shadow: none !important;
  height: 32px;
  line-height: 32px;
}

::v-deep .name-form-item .el-form-item__error {
  color: red !important;
  font-size: 12px !important;
  line-height: 1.2 !important;
  position: absolute !important;
  top: 36px !important;
  left: 0 !important;
  width: 510px !important;
  max-width: 100% !important;
  margin: 0 !important;
  padding: 0 !important;
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
  z-index: 10 !important;
  white-space: normal !important;
}

.full-divider {
  width: 100%;
  height: 1px;
  background-color: #e4e7ed;
  margin: 8px 0;
}

.progress-section {
  width: 900px;
  max-width: 100%;
  margin: 0 auto 25px;
  box-sizing: border-box;
  background-color: #ffffff !important;
  overflow-x: hidden !important;
  overflow-y: visible !important;
  height: auto !important;
}

.custom-steps-container {
  width: 100% !important;
  margin-left: 0 !important;
  padding: 0 10px;
  overflow-x: hidden !important;
  overflow-y: visible !important;
  height: auto !important;
}

.custom-steps {
  display: flex !important;
  align-items: flex-start !important;
  width: 100% !important;
  gap: 15px !important;
  flex-wrap: nowrap !important;
  height: auto !important;
}

::v-deep .step-item {
  display: flex !important;
  align-items: center !important;
  flex: 1 !important;
  position: relative !important;
  min-width: 0 !important;
  margin: 0 !important;
  padding: 0 5px !important;
  height: auto !important;
  transform-origin: left center;
}

::v-deep .third-step {
  padding-right: 8px !important;
}

::v-deep .el-step__head {
  width: auto !important;
  height: auto !important;
  padding: 0 !important;
  margin: 0 !important;
  min-width: unset !important;
  background: transparent !important;
}

::v-deep .el-step__main {
  display: flex !important;
  align-items: center !important;
  flex-direction: row !important;
  padding: 0 !important;
  margin: 0 !important;
}

::v-deep .el-step__title {
  line-height: 1.3 !important;
  padding: 2px 0 !important;
  margin: 2px 0 !important;
  margin-left: 8px !important;
  color: inherit !important;
}

::v-deep .el-step__line-inner {
  display: none !important;
}

.form-section {
  width: 700px;
  max-width: 100%;
  margin: 0 auto;
  min-height: auto;
  max-height: calc(100vh - 250px);
  overflow: auto !important;
  box-sizing: border-box;
  background-color: #ffffff !important;
  overflow-x: hidden !important;
  padding: 0 5px;
}

.wide-form {
  width: 1200px;
  max-width: 100%;
  max-height: none;
  overflow: visible !important;
  overflow-x: hidden !important;
  padding: 0 10px;
}

.full-width-form {
  width: 100%;
  max-height: none;
  overflow: visible !important;
  overflow-x: hidden !important;
}

.button-group {
  width: 100%;
  margin: 20px auto 0;
  text-align: center !important;
  box-sizing: border-box;
  background-color: #ffffff !important;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  position: fixed !important;
  bottom: 0 !important;
  left: 0 !important;
  padding: 15px 20px !important;
  box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.03);
  z-index: 1000 !important;
  overflow-x: hidden !important;
}

.button-group .el-button {
  margin: 0 15px !important;
}

::v-deep .custom-loading .el-loading-spinner circle {
  stroke: #1E60FA !important;
  stroke-width: 2px !important;
  stroke-opacity: 0.3 !important;
}

@media (max-width: 1366px) {
  .progress-section {
    margin-left: 0 !important;
  }

  .custom-steps-container {
    padding: 0 10px;
  }

  .custom-steps {
    gap: 10px !important;
  }

  ::v-deep .step-item .el-step__title {
    font-size: 13px !important;
  }

  .button-group .el-button {
    margin: 0 10px !important;
  }
}

@media (max-width: 1280px) {
  .paper-name-input {
    width: 450px;
  }

  .custom-steps {
    gap: 5px !important;
  }
}

@media (max-width: 1090px) {
  ::v-deep .custom-step-line {
    left: calc(100% - 110px) !important;
  }

  ::v-deep .step-item .el-step__title {
    margin-left: 15px !important;
  }
}

@media (max-width: 1100px) {
  .paper-name-input {
    width: 400px;
  }

  ::v-deep .step-item .el-step__title {
    white-space: normal !important;
    text-align: center;
    margin-left: 0 !important;
    margin-top: 5px;
    font-size: 12px !important;
    line-height: 1.2 !important;
  }

  ::v-deep .el-step__main {
    flex-direction: column !important;
    align-items: center !important;
  }

  .custom-steps {
    align-items: center !important;
    gap: 3px !important;
  }

  ::v-deep .step-item {
    transform: none !important;
  }
}

@media (max-width: 900px) {
  .app-container {
    padding: 40px 15px 70px;
  }

  .paper-name-input {
    width: 100% !important;
  }

  .button-group .el-button {
    margin: 0 8px !important;
    padding: 6px 12px !important;
    font-size: 13px !important;
  }

  .custom-steps {
    gap: 2px !important;
  }
}

@media (max-width: 768px) {
  .name-input-wrapper {
    flex-wrap: wrap !important;
  }

  .paper-name-label {
    width: 100%;
    margin-bottom: 8px;
  }

  .button-group .el-button {
    margin: 0 5px !important;
    font-size: 11px !important;
    padding: 5px 10px !important;
  }

  ::v-deep .step-item .el-step__title {
    font-size: 11px !important;
  }
}
</style>

<style>
.sidebar,
.sidebar-container,
.el-layout__sider,
.sidebar-wrap {
  visibility: hidden !important;
  width: 0px !important;
  height: 0px !important;
  padding: 0 !important;
  margin: 0 !important;
  overflow: hidden !important;
  display: block !important;
}

.main-container,
.app-main,
.el-layout,
.el-layout__content {
  width: 100% !important;
  margin: 0 !important;
  padding: 0 !important;
  overflow: hidden !important;
  background-color: #ffffff !important;
  z-index: 1 !important;
  overflow-x: hidden !important;
}

body,
html,
#app {
  overflow: hidden !important;
  background-color: #ffffff !important;
  overflow-x: hidden !important;
}

.el-form,
.el-row,
.el-col {
  width: 100%;
  box-sizing: border-box;
}

.el-input__inner,
.el-textarea__inner {
  background-color: #EEF4FA !important;
  border: none !important;
  box-shadow: none !important;
}

.wide-form .el-input__inner {
  background-color: #fff !important;
}

.el-message {
  z-index: 9999 !important;
  margin-top: 10px !important;
  max-width: 90% !important;
  white-space: normal !important;
}

/* 加载动画关键帧（确保转圈流畅） */
@keyframes loading-dash {
  0% {
    stroke-dasharray: 1, 200;
    stroke-dashoffset: 0;
  }

  50% {
    stroke-dasharray: 90, 150;
    stroke-dashoffset: -40px;
  }

  100% {
    stroke-dasharray: 90, 150;
    stroke-dashoffset: -120px;
  }
}
</style>